<template>
  <div class="page-mobile-course_detail" id="page-mobile-course_detail">
    <no-ssr>
      <white-header
        :isShowTopNav="true"
        :isShowBack="true"
        :isShowRight="true"
        :title="course_obj.courseName"
      ></white-header>
      <div
        class="collection"
        @click="collectionHandle"
        v-if="token && Object.keys(user_info).length > 0"
      >
        <img
          src="/img/mobile/answer_collection.png"
          alt=""
          :style="{
            backgroundColor:
              course_obj.isCollect === 1 ? 'var(--theme-color)' : '#c8c9cc'
          }"
        />
      </div>
      <div class="course-info">
        <div class="course-img">
          <img :src="course_obj.iconPath" alt="" />
        </div>
        <div class="course-name">
          {{ course_obj.courseName }}
        </div>
        <div class="student-price" v-if="!is_hidden_content && !is_had_course">
          <div class="price" v-show="!is_show_price">
            ￥<span style="font-size: .4416rem;">
              <!-- 拼团显示价格 -->
              <template
                v-if="
                  kl_md.KLPT == 1 &&
                    gbConfig.is_set &&
                    group_booking_status == 1
                "
              >
                <span>
                  {{ gbConfig.lastMoney }}
                </span>
                <span class="sub-price"> ￥{{ course_obj.price }} </span>
              </template>
              <!-- 非拼团显示价格 -->
              <template v-else>
                <!-- 折扣 -->
                <span v-if="course_obj.isDiscount">
                  {{ course_obj.isFree ? 0 : course_obj.discountPrice }}
                </span>
                <!-- 非折扣 -->
                <span v-if="!course_obj.isDiscount">
                  {{
                    Number(
                      course_obj.isFree //免费
                        ? 0
                        : isMemberFree //会员免费
                        ? 0
                        : !is_member //非会员
                        ? course_obj.price //原价
                        : user_member.memberLevel === 0
                        ? course_obj.smallMemberPrice
                        : user_member.memberLevel === 1
                        ? course_obj.middleMemberPrice
                        : user_member.memberLevel === 2
                        ? course_obj.highMemberPrice
                        : 0
                    ).toFixed(2)
                  }}
                </span>
              </template>
            </span>
          </div>
          <div class="student">{{ course_obj.studentSum }}人已购买</div>
        </div>
        <div class="teacher">
          <div
            class="teacher-left"
            @click="$router.push('/m/teacher-detail?id=' + course_obj.teacher)"
          >
            <div class="teacher-avatar">
              <img :src="course_obj.avatar" alt="" />
            </div>
            <div class="teacher-name">{{ course_obj.acName }}</div>
            <img src="/img/mobile/right-icon.png" alt="" />
          </div>
          <div class="teacher-right">
            <template v-if="false">
              <img src="/img/mobile/lubo.png" alt="" />
              <div class="count-time">总时长34小时24分钟</div>
            </template>
          </div>
        </div>
      </div>
      <!-- 拼团 -->
      <div
        class="group-booking"
        v-if="
          !is_hidden_content &&
            !is_show_price &&
            kl_md.KLPT == 1 &&
            !is_had_course &&
            course_obj.isFree != 1 &&
            groupNum > 0
        "
      >
        <div class="group-booking-info">
          <div class="info-left">{{ groupNum }}人在拼单，可直接参与</div>
          <div class="info-right" @click="is_groupBooking_dialog = true">
            <div class="coupon-right">查看更多<van-icon name="arrow" /></div>
          </div>
        </div>
        <div class="group-booking-list" v-if="groupList.length > 0">
          <van-swipe
            class="list-container"
            vertical
            :autoplay="5000"
            :show-indicators="false"
            :touchable="false"
          >
            <van-swipe-item
              v-for="(item, index) in Math.floor(groupList.length / 2) == 0
                ? 1
                : Math.floor(groupList.length / 2)"
              :key="index"
            >
              <div
                class="list-item"
                v-for="(item1, index2) in [
                  groupList[2 * index], //第一项
                  //第二项：当遍历到上面对象最后一个对象时，如果为偶数正常渲染，为奇数只显示一个；当groupList长度为1的时候也只显示一个
                  (index == Math.floor(groupList.length / 2) - 1 &&
                    groupList.length % 2 != 0) ||
                  Math.floor(groupList.length / 2) == 0
                    ? null
                    : groupList[2 * index + 1]
                ]"
                v-if="item1 !== null"
                :key="index2"
              >
                <div class="item-left">
                  <div class="user-avatar">
                    <img
                      v-lazy="item1 && item1.userList[0].avatar"
                      v-if="item1 && item1.userList[0].avatar"
                    />
                    <span
                      v-if="item1 && !item1.userList[0].avatar"
                      class="avatar-alt"
                    >
                      {{
                        item1 &&
                          item1.userList[0].acName &&
                          item1.userList[0].acName.substring(0, 1)
                      }}
                    </span>
                  </div>
                  <div class="user-nackname">
                    {{ item1 && item1.userList[0].acName }}
                  </div>
                </div>
                <div class="item-content">
                  <div class="content-top">
                    还差{{
                      item1 && (item1.maxNum - item1.personNum || "?")
                    }}人拼成
                  </div>
                  <div class="content-bottom">
                    <van-count-down
                      :time="getGroupCount(item1)"
                      v-if="getGroupCount(item1) != -1"
                      millisecond
                      @finish="handleFinish('list', item1)"
                    >
                      <template v-slot="timeData">
                        <span class="block">{{
                          twoNumber(timeData.hours)
                        }}</span>
                        <span class="colon">:</span>
                        <span class="block">{{
                          twoNumber(timeData.minutes)
                        }}</span>
                        <span class="colon">:</span>
                        <span class="block">{{
                          twoNumber(timeData.seconds)
                        }}</span>
                        <!-- <span class="colon">:</span>
                        <span class="block">{{
                          twoNumber(timeData.milliseconds)
                        }}</span> -->
                      </template>
                    </van-count-down>
                  </div>
                </div>
                <div class="item-right">
                  <van-button
                    type="primary"
                    block
                    @click="handleJoinGroup(item1)"
                    >去拼单</van-button
                  >
                </div>
              </div>
            </van-swipe-item>
          </van-swipe>
        </div>
      </div>

      <div
        class="coupon"
        @click="showCoupon = true"
        v-if="
          kl_md.KLYHJ == 1 &&
            !is_had_course &&
            course_obj.isFree != 1 &&
            couponList &&
            couponList.length > 0
        "
      >
        <div class="coupon-left">
          优惠卷
        </div>
        <div class="coupon-right">查看<van-icon name="arrow" /></div>
      </div>
      <div
        :class="[
          'course-menu',
          is_had_course && kl_md.KLZYGL == 1 ? 'task_item' : ''
        ]"
        v-if="isFixedNav"
      >
        <div
          :class="['menu-item', active == 'introduce' ? 'active' : '']"
          @click="menuHandle('introduce')"
        >
          课程介绍
        </div>
        <div
          :class="['menu-item', active == 'chapter' ? 'active' : '']"
          @click="menuHandle('chapter')"
        >
          课程章节
        </div>
        <div
          :class="['menu-item', active == 'file' ? 'active' : '']"
          @click="menuHandle('file')"
        >
          学习课件
        </div>
        <div
          v-if="is_had_course && kl_md.KLZYGL == 1"
          :class="['menu-item', active == 'task' ? 'active' : '']"
          @click="menuHandle('task')"
        >
          课程作业
        </div>
      </div>
      <div
        :class="[
          'course-menu',
          isFixedNav ? 'fixed' : '',
          is_had_course && kl_md.KLZYGL == 1 ? 'task_item' : ''
        ]"
      >
        <div
          :class="['menu-item', active == 'introduce' ? 'active' : '']"
          @click="menuHandle('introduce')"
        >
          课程介绍
        </div>
        <div
          :class="['menu-item', active == 'chapter' ? 'active' : '']"
          @click="menuHandle('chapter')"
        >
          课程章节
        </div>
        <div
          :class="['menu-item', active == 'file' ? 'active' : '']"
          @click="menuHandle('file')"
        >
          学习课件
        </div>
        <div
          v-if="is_had_course && kl_md.KLZYGL == 1"
          :class="['menu-item', active == 'task' ? 'active' : '']"
          @click="menuHandle('task')"
        >
          课程作业
        </div>
      </div>
      <div class="course-container">
        <div class="course-introduce" ref="course-introduce">
          <div class="title">课程介绍</div>
          <div class="ql-snow">
            <div class="ql-editor" v-html="course_obj.introduce"></div>
          </div>
        </div>
        <div class="course-chapter" ref="course-chapter">
          <div class="title">课程章节</div>
          <div class="chapter-box">
            <div
              class="chapter-list"
              v-for="(itemOne, indexOne) in chapter_tree"
              :key="indexOne"
            >
              <template v-if="itemOne.children.length > 0">
                <div class="chapter-title-one">{{ itemOne.chapterName }}<span style="margin-left:.2rem;" v-if="itemOne.duration">{{ itemOne.duration }}</span></div>
                <div
                  v-for="(itemTwo, indexTwo) in itemOne.children"
                  :key="indexTwo"
                >
                  <template v-if="itemTwo.children.length > 0">
                    <!-- <div class="chapter-title-one">
                      {{ itemOne.chapterName }}
                    </div> -->
                    <div class="chapter-list">
                      <div class="chapter-title-two">
                        {{ itemTwo.chapterName }}<span style="margin-left:.2rem;" v-if="itemTwo.duration">{{ itemTwo.duration }}</span>
                      </div>
                      <div
                        class="chapter-one"
                        v-for="(itemThree, indexThree) in itemTwo.children"
                        :key="indexThree"
                        @click="pushRouter(itemThree)"
                      >
                        <template
                          v-if="
                            is_in_wechat &&
                              !is_in_minigram &&
                              itemThree.isLive == 2 &&
                              !itemThree.videoInfo
                          "
                        >
                          <wx-open-launch-weapp
                            :class="['chapter-left', 'launch-btn']"
                            :username="wxMinigramInfo.miniAppid"
                            :path="wxLivePath(itemThree)"
                          >
                            <script type="text/wxtag-template">
                              <div>
                                {{ itemThree.chapterName }}<span style="margin-left:.2rem;" v-if="itemThree.duration">{{ itemThree.duration }}</span>
                              </div>
                            </script>
                          </wx-open-launch-weapp>
                        </template>
                        <template v-else>
                          <div class="chapter-left">
                            {{ itemThree.chapterName }}<span style="margin-left:.2rem;" v-if="itemThree.duration">{{ itemThree.duration }}</span>
                          </div>
                        </template>
                        <div class="chapter-right" v-if="itemThree.isJump == 1">
                          免费试学
                        </div>
                      </div>
                    </div>
                  </template>
                  <template v-else>
                    <!-- <div class="chapter-title-one">{{itemOne.chapterName}}</div> -->
                    <div class="chapter-list">
                      <div class="chapter-one" @click="pushRouter(itemTwo)">
                        <template
                          v-if="
                            is_in_wechat &&
                              !is_in_minigram &&
                              itemTwo.isLive == 2 &&
                              !itemTwo.videoInfo
                          "
                        >
                          <wx-open-launch-weapp
                            :class="['chapter-left', 'launch-btn']"
                            :username="wxMinigramInfo.miniAppid"
                            :path="wxLivePath(itemTwo)"
                          >
                            <script type="text/wxtag-template">
                              <div>
                                {{ itemTwo.chapterName }}<span style="margin-left:.2rem;" v-if="itemTwo.duration">{{ itemTwo.duration }}</span>
                              </div>
                            </script>
                          </wx-open-launch-weapp>
                        </template>
                        <template v-else>
                          <div class="chapter-left">
                            {{ itemTwo.chapterName }}<span style="margin-left:.2rem;" v-if="itemTwo.duration">{{ itemTwo.duration }}</span>
                          </div>
                        </template>
                        <div class="chapter-right" v-if="itemTwo.isJump == 1">
                          免费试学
                        </div>
                      </div>
                    </div>
                  </template>
                </div>
              </template>
              <template v-else>
                <div>
                  <div class="chapter-list">
                    <div class="chapter-two" @click="pushRouter(itemOne)">
                      <template
                        v-if="
                          is_in_wechat &&
                            !is_in_minigram &&
                            itemOne.isLive == 2 &&
                            !itemOne.videoInfo
                        "
                      >
                        <wx-open-launch-weapp
                          :class="['chapter-left', 'launch-btn']"
                          :username="wxMinigramInfo.miniAppid"
                          :path="wxLivePath(itemOne)"
                        >
                          <script type="text/wxtag-template">
                            <div>
                              {{ itemOne.chapterName }}<span style="margin-left:.2rem;" v-if="itemOne.duration">{{ itemOne.duration }}</span>
                            </div>
                          </script>
                        </wx-open-launch-weapp>
                      </template>
                      <template v-else>
                        <div class="chapter-left">
                          {{ itemOne.chapterName }}<span style="margin-left:.2rem;" v-if="itemOne.duration">{{ itemOne.duration }}</span>
                        </div>
                      </template>
                      <div class="chapter-right" v-if="itemOne.isJump == 1">
                        免费试学
                      </div>
                    </div>
                  </div>
                </div>
              </template>
            </div>
          </div>
        </div>
        <div class="course_comment" v-if="kl_md.KLKCPJ == 1">
          <p class="comment_title">
            <span>学员评论({{commentTotal}})</span>
            <span @click="allCommentHandle" v-if="commentTotal > 0">查看全部</span>
          </p>
          <p class="comment_empty" v-if="commentTotal == 0">暂无评论</p>
          <ul class="comment_list" v-else>
            <li class="comment_item" v-for="(item,index) in commentList" :key="item.id">
              <div class="comment_user">
                <img :src="item.avatar ? item.avatar : '/img/mobile/user_nav_head.png'" class="comment_avatar" alt="" />
                <div>
                  <p class="comment_username">{{item.acName}}</p>
                  <p class="comment_rate">
                    <van-rate :value="item.rate" readonly size="14px" />
                  </p>
                </div>
                <van-tag class="top_tag" plain type="primary" v-if="item.isTop">置顶</van-tag>
              </div>
              <div class="comment_content">
                <div class="comment_text">
                  <p v-if="item.content">{{item.content}}</p>
                  <p v-else>{{item.rate | formatRate}}</p>
                </div>
                <p class="comment_time">{{trimDate(item.createTime)}}</p>
              </div>
            </li>
          </ul>
        </div>
        <div
          :class="[
            'course-file',
            is_had_course && kl_md.KLZYGL == 1
              ? 'course_task'
              : 'un_course_task'
          ]"
          ref="course-file"
        >
          <div class="title">学习课件</div>
          <div
            class="file-item"
            v-if="
              token &&
                Object.keys(user_info).length > 0 &&
                is_had_course &&
                item.courseWarePath &&
                item.courseWarePath != 'null'
            "
            v-for="(item, index) in courseWarePathList"
            :key="index"
          >
            <div class="item-left">{{ item.chapterName }}课件</div>
            <a
			  :href="item.courseWarePath"
			  :download="item.chapterName"
              class="item-right"
            >
              <!-- <a :href="item.courseWarePath" :download="item.chapterName"
                >{{item.courseWarePath ? '下载' : '暂无'}}</a
              > -->
              {{ item.courseWarePath ? "下载" : "暂无" }}
            </a>
          </div>
        </div>
        <div
          class="course-task"
          ref="course-task"
          v-if="is_had_course && kl_md.KLZYGL == 1"
        >
          <div class="title">课程作业</div>
          <div
            class="task-item"
            v-if="is_had_course && kl_md.KLZYGL == 1"
            v-for="(item, index) in myTaskList"
            :key="index"
          >
            <div class="item-left">
              【{{ item.videoName }}】{{ item.taskName }}
            </div>
            <div class="item-right">
              <Upload
                class="avatar-uploader"
                ref="avatar-uploader"
                action=""
                :before-upload="afterRead"
                :show-file-list="false"
                :auto-upload="false"
                :show-upload-list="false"
                @click="false"
                v-if="item.taskType == 2"
              >
                <van-button
                  type="primary"
                  size="small"
                  class="submit_btn"
                  @click="setTask(item)"
                  :disabled="!!item.userTask"
                  >{{ item.userTask ? "已经完成" : "上传作业" }}</van-button
                >
              </Upload>
              <van-button
                type="primary"
                size="small"
                class="submit_btn"
                @click="setTask(item)"
                :disabled="!!item.userTask"
                v-else
                >{{ item.userTask ? "已经完成" : "开始考试" }}</van-button
              >
            </div>
          </div>
        </div>
      </div>
      <!-- 常规底部按钮 -->
      <div
        class="bottom-area"
        v-if="
          !is_hidden_content &&
            (kl_md.KLPT != 1 || !gbConfig.is_set || group_booking_status != 1)
        "
        v-show="(!is_show_price || course_obj.isFree == 1) && !is_had_course"
      >
        <div class="btn-buy">
          <van-button type="primary" block @click="toBuy" :class="[ buyStatus ? 'graystyle' : '']">{{
            buyStatus ? "尚未开放":course_obj.isFree
              ? $t("locale.mobile.courseDetail.t21")
              : is_hidden_for_ios
              ? "立即报名"
              : $t("locale.mobile.courseDetail.t17")
          }}</van-button>
        </div>
      </div>
      <!-- 带拼团底部按钮 -->
      <div
        class="bottom-area gb"
        v-if="
          !is_hidden_content &&
            kl_md.KLPT == 1 &&
            gbConfig.is_set &&
            group_booking_status == 1
        "
        v-show="!is_show_price && !is_had_course"
      >
        <div class="btn-buy">
          <van-button
            type="primary"
            block
            @click="toBuy"
            :style="{
              backgroundColor: THEME_COLOR_LIGHTER,
              borderColor: THEME_COLOR_LIGHTER
            }"
            :class="['btn-left',buyStatus ? 'graystyle' : '']"
          >
            <div class="btn-price">￥{{ course_obj.price }}</div>
            <div class="btn-text">单独购买</div>
          </van-button>
          <van-button
            type="primary"
            block
            @click="joinGroup('self')"
            :disabled="isPublishedBefore"
            :class="['btn-right',buyStatus ? 'graystyle' : '']"
          >
            <div class="btn-price">￥{{ gbConfig.lastMoney }}</div>
            <div class="btn-text">发起拼单</div>
          </van-button>
        </div>
      </div>
      <van-action-sheet v-model="showCoupon" title="领取优惠卷">
        <div
            class="coupon-content"
            v-for="(item, index) in couponList"
            :key="item.id"
          >
            <div class="coupon-box">
              <div class="box-left">
                <div class="right-line"></div>
                <div class="price">
                  ￥<span>{{ item.couponAmount }}</span>
                </div>
                <div class="info">
                  <div class="max-time">
                    <span v-if="item.couponType == 0"
                      >满{{ item.conditionalAmount }}可用</span
                    >
                    <span v-if="item.couponType == 1">无门槛</span>
                  </div>
                  <div class="info-time">
                    有效期至 {{ formatDate(item.endTime) }}
                  </div>
                </div>
              </div>
              <div class="box-right" @click="receiveCoupon(item.id)">
                立即领取
              </div>
            </div>
          </div>
        <!-- <div
          class="coupon-content"
          v-for="(item, index) in course_obj.coupons"
          :key="item.id"
        >
          
        </div> -->
      </van-action-sheet>

      <!-- 拼团列表弹窗列表 -->
      <van-dialog
        v-model="is_groupBooking_dialog"
        title="正在拼单"
        show-cancel-button
        get-container="#page-mobile-course_detail"
        class="groupBooking_dialog"
        confirmButtonText="确定"
        cancelButtonText="取消"
        :showCancelButton="false"
      >
        <div class="list-container">
          <div
            class="list-item"
            v-for="(item, index) in groupList"
            :key="index"
          >
            <div class="item-left">
              <div class="user-avatar">
                <img
                  v-lazy="item.userList[0].avatar"
                  v-if="item.userList[0].avatar"
                />
                <span v-if="!item.userList[0].avatar" class="avatar-alt">
                  {{
                    item.userList[0].acName &&
                      item.userList[0].acName.substring(0, 1)
                  }}
                </span>
              </div>
              <div class="user-nackname">{{ item.userList[0].acName }}</div>
            </div>
            <div class="item-content">
              <div class="content-top">
                还差{{ item.maxNum - item.personNum || "？" }}人拼成
              </div>
              <div class="content-bottom">
                <van-count-down
                  :time="getGroupCount(item)"
                  v-if="getGroupCount(item) != -1"
                  @finish="handleFinish('list', item)"
                  millisecond
                >
                  <template v-slot="timeData">
                    <span class="block">{{ twoNumber(timeData.hours) }}</span>
                    <span class="colon">:</span>
                    <span class="block">{{ twoNumber(timeData.minutes) }}</span>
                    <span class="colon">:</span>
                    <span class="block">{{ twoNumber(timeData.seconds) }}</span>
                    <span class="colon">:</span>
                    <span class="block">{{
                      twoNumber(timeData.milliseconds)
                    }}</span>
                  </template>
                </van-count-down>
              </div>
            </div>
            <div class="item-right">
              <van-button type="primary" block @click="handleJoinGroup(item)"
                >去拼单</van-button
              >
            </div>
          </div>
        </div>
      </van-dialog>

      <!-- 参与拼团弹窗 -->
      <van-dialog
        v-model="is_groupBooking_join"
        :title="'参加' + current_group.userList[0].acName + '的拼单'"
        show-cancel-button
        get-container="#page-mobile-course_detail"
        class="groupBooking_join"
        confirmButtonText="参与拼单"
        cancelButtonText="取消"
        @confirm="joinGroup('group')"
      >
        <div class="join-container">
          <div class="join-rest">
            仅限<span class="rest-num">{{
              current_group.maxNum - current_group.personNum || "?"
            }}</span
            >个名额，<van-count-down
              :time="getGroupCount(current_group)"
              v-if="getGroupCount(current_group) != -1"
              millisecond
              @finish="handleFinish('current')"
            >
              <template v-slot="timeData">
                <span class="block">{{ twoNumber(timeData.hours) }}</span>
                <span class="colon">:</span>
                <span class="block">{{ twoNumber(timeData.minutes) }}</span>
                <span class="colon">:</span>
                <span class="block">{{ twoNumber(timeData.seconds) }}</span>
                <!-- <span class="colon">:</span>
              <span class="block">{{ twoNumber(timeData.milliseconds) }}</span> -->
              </template> </van-count-down
            >后结束
          </div>
          <div class="group-member">
            <div
              :class="[
                'member-item',
                item.id == current_group.userId && 'leader'
              ]"
              v-for="(item, index) in current_group.userList"
            >
              <van-tag type="primary" v-if="item.id == current_group.userId"
                >拼主</van-tag
              >
              <img v-lazy="item.avatar" v-if="item.avatar" />
              <span v-if="!item.avatar" class="avatar-alt">
                {{ item.acName && item.acName.substring(0, 1) }}
              </span>
            </div>
            <template v-if="current_group.personNum < current_group.maxNum">
              <div
                class="member-item pending"
                v-for="(item, index) in current_group.maxNum -
                  current_group.personNum"
              >
                <Icon type="ios-help" />
              </div>
            </template>
          </div>
          <!-- <van-button type="primary" block @click="joinGroup"
          >参与拼单</van-button
        > -->
        </div>
      </van-dialog>
      <div
        class="course-agreement"
        v-if="isShowCourseAgreement && kl_md.KLKCXY == 1"
      >
        <div class="agreement-box">
          <div class="agreement-header">课程协议</div>
          <div class="agreement-body">
            <div class="ql-snow">
              <div
                class="ql-editor"
                v-html="
                  courseAgreementObj && courseAgreementObj.agreementContent
                "
              ></div>
            </div>
          </div>
          <div class="agreement-footer">
            <van-form @submit="handleSubmitAgreement">
              <van-field
                v-model="agreementForm.userName"
                name="userName"
                label="姓名"
                placeholder="请输入姓名"
                :rules="[{ required: true, message: '请输入姓名' }]"
              />
              <van-field
                v-model="agreementForm.idNumber"
                type="text"
                name="idNumber"
                label="身份证"
                placeholder="请输入身份证"
                :rules="[
                  {
                    validator: validateIdNumber,
                    message: '请输入正确的身份证号'
                  }
                ]"
              />
              <div style="margin: 16px;">
                <van-button round block type="info" native-type="submit"
                  >同意</van-button
                >
              </div>
            </van-form>
          </div>
        </div>
      </div>
    </no-ssr>
  </div>
</template>

<script>
import { getCourse,getCourseCommentList } from "~/api/course";
import {
  getCourseAgreement,
  saveCourseAgreement
} from "~/api/course-agreement";
import { getChapter, getVideoLastTime } from "~/api/chapter";
import { getTeacher } from "~/api/account/user";
import { downloadFile } from "~/api/common";
import { saveOrder } from "~/api/order";
import { receiveCoupon, getCourseCoupon } from "~/api/coupon";
import { mapState, mapActions, mapMutations } from "vuex";
import WhiteHeader from "~/components/mobile/WhiteHeader.vue";
import { getMimeType } from "~/utils/commonfun";
import { blobToDataURL } from "~/utils/file";
import { getMyTaskList, saveUserTask, getVideoUrl } from "~/api/task";
import {
  getGroupBookingListByCourse,
  getGroupBookingGroupsByCourse,
  getGroupBookingGroupsByCourseAndUser
} from "~/api/group-booking";
import {
  saveCollection,
  deleteCollection,
  getCollectList
} from "~/api/v2-question-bank/question-bank.js";
import {
  getMemberInfo,
  getMember,
  getMemberList,
  getMemberConfig
} from "~/api/member";
import { launchWxMiniProgram } from "~/utils/pay";
import { getWxMiniInfo } from "~/api/site";

const originState = {
  myTaskList: [],
  taskObj: {},
  courseAgreementObj: null,
  agreementForm: {},
  couponList: [], //课程对应的优惠卷
  showCoupon: false,
  isFixedNav: false,
  active: "introduce",
  course_obj: {
    name: "",
    isFree: 0
  },
  teacher_obj: {}, //课程老师信息
  chapter_list: [], //章节列表
  chapter_tree: [], //章节树
  chapter_active: [], //折叠面板打开
  chapter_obj: {
    courseId: 0,
    chapterName: "",
    chapterIndex: 1,
    chapterLevel: 1,
    chapterDescription: "",
    fatherLevelId: 0,
    live: "hahah",
    courseWarePath: null,
    fileName: "",
    filePath: "",
    fileType: null,
    fileSize: null,
    createTime: 1591012869000,
    createUserId: null,
    createUserName: null,
    updateTime: 1591012869000,
    updateUserId: null,
    updateUserName: null,
    liveEndTime: 1591012869000,
    liveStartTime: 1591012869000,
    isLive: 0
  },
  //正在播放的章节
  video_obj: {
    time: 0
  }, //视频其他数据
  websock: null,
  component: "ChapterTree",
  component1: "ChapterWareTree",
  sources: "",
  is_had_course: false,
  last_require_lime: new Date().getTime(), //上次上报视频时间的时间戳
  member_config: {
    isOpenMember: 0
  },
  memberList: [],
  groupList: [], //拼团列表
  groupNum: 0, //正在拼团的个数
  is_groupBooking_dialog: false, //拼团列表更多弹窗
  is_groupBooking_join: false, //参与拼团弹窗
  gbConfig: {
    creatTime: 1613703969931,
    endTime: 1629255969931,
    goodsId: 12,
    id: 5,
    imitate: 1,
    lastMoney: 1800,
    personNum: 2,
    startTime: 1613703969931,
    troopsTime: 1440,
    is_set: false // 是否是拼团商品
  }, //拼团信息
  current_group: {
    //选择的拼团
    creatTime: 0,
    goodsId: -1,
    personNum: -1,
    userId: -1,
    userIds: [],
    userList: [
      {
        acName: "",
        avatar: "",
        id: -1
      }
    ]
  },
  isPublishedBefore: false, //是否发起过拼单
  /* 微信小程序相关 */
  wxMinigramInfo: {
    appId: "",
    nonceStr: "",
    sign: "",
    timeStamp: "",
    miniAppid: ""
  }
};

export default {
  scrollToTop: true,
  components: {
    WhiteHeader
  },
  // head() {
  //   return {
  //     meta: this.is_set_secure
  //       ? [
  //           {
  //             hid: "http-equiv",
  //             "http-equiv": "Content-Security-Policy",
  //             name: "Content-Security-Policy",
  //             content: "upgrade-insecure-requests"
  //           }
  //         ]
  //       : []
  //   };
  // },
  data() {
    return {
      ...originState,
      commentList:[],
      commentTotal:0,
    };
  },
  filters:{
    formatRate(val){
      switch (val) {
        case 1:
          return "差评！课程太差了，我要吐槽！";
        case 2:
          return "勉强中评！课程不满意";
        case 3:
          return "中评！课程一般";
        case 4:
          return "好评！课程还不错，继续保持！";
        case 5:
          return "五星好评！课程非常棒，点赞！";
        default:
          return "";
      }
    }
  },
  computed: {
    ...mapState({
      user_info(state) {
        return state.user_info;
      },
      major_list(state) {
        return state.major_list;
      },
      buy_record_list(state) {
        return state.buy_record_list;
      },
      sign_Agreement_list(state) {
        return state.sign_Agreement_list;
      },
      is_mobile(state) {
        return state.is_mobile;
      },
      token(state) {
        return state.token;
      },
      is_ios(state) {
        return state.is_ios;
      },
      is_in_wechat(state) {
        return state.is_in_wechat;
      },
      is_in_minigram(state) {
        return state.is_in_minigram;
      },
      is_hidden_content(state) {
        return state.is_hidden_content;
      },
      is_member(state) {
        return JSON.stringify(state.member_info) != "{}";
      },
      user_member(state) {
        return state.member_info;
      },
      member_discount(state) {
        return state.member_discount;
      },
      kl_md(state) {
        return state.kl_md;
      },
      is_wechat_ios_limit(state) {
        return state.is_wechat_ios_limit;
      },
      is_hidden_for_ios(state) {
        return state.is_hidden_for_ios;
      },
      THEME_COLOR_LIGHTER(state) {
        return state.THEME_COLOR_LIGHTER;
      }
    }),
    buyStatus(){
      let startTime = this.course_obj.buyCourseStartDate;
      let endTime = this.course_obj.buyCourseDeadlineDate;
      let nowTime = new Date().getTime();
      if(startTime > nowTime || endTime < nowTime){
        return true;
      }else{
        return false;
      }
    },
    isShowCourseAgreement() {
      if (
        this.is_had_course &&
        this.courseAgreementObj &&
        Object.keys(this.courseAgreementObj).length > 0
      ) {
        let obj = this.sign_Agreement_list.findIndex(item => {
          return item.agreementId == this.courseAgreementObj.id;
        });
        if (obj != -1) {
          return false;
        } else {
          return true;
        }
      } else {
        return false;
      }
    },
    isMemberFree() {
      if (
        this.member_discount &&
        JSON.stringify(this.member_discount) !== "{}"
      ) {
        if (
          this.member_discount.majorIds.includes(this.course_obj.majorId) ||
          this.member_discount.courseIds.includes(this.course_obj.id)
        ) {
          return true;
        } else {
          return false;
        }
      }
    },
    is_show_price() {
      if (this.is_wechat_ios_limit) {
        return this.is_ios && this.is_in_wechat;
      } else {
        return false;
      }
    },
    courseId() {
      return this.$route.query.id;
    },
    chapterId() {
      return this.$route.query.chapterId;
    },
    isMircosoftRead() {
      const { courseWarePath } = this.chapter_obj;
      let xls = /^.*\.(?:xls)$/;
      let xlsx = /^.*\.(?:xlsx)$/;
      let docx = /^.*\.(?:docx)$/;
      let doc = /^.*\.(?:doc)$/;
      let ppt = /^.*\.(?:ppt)$/;
      let pptx = /^.*\.(?:pptx)$/;
      if (
        xls.test(courseWarePath) ||
        xlsx.test(courseWarePath) ||
        doc.test(courseWarePath) ||
        docx.test(courseWarePath) ||
        pptx.test(courseWarePath) ||
        ppt.test(courseWarePath)
      ) {
        return true;
      } else {
        return false;
      }
    },
    getCount() {
      let time_far = this.course_obj.discountEndTime - new Date().getTime();
      if (time_far > 0) {
        return time_far;
      } else {
        return -1;
      }
    },
    getChapterCount() {
      let time_far = this.chapter_obj.liveStartTime - new Date().getTime();
      if (time_far > 0) {
        return time_far;
      } else {
        return -1;
      }
    },
    courseWarePathList() {
      let wareList = this.chapter_list.filter(item => item.courseWarePath);
      // console.log("wareList",wareList);
      return wareList;
    },
    is_set_secure() {
      if (process.client) {
        let is_https_resource = /^https/.test(this.chapter_obj.live);
        let is_https_domain = window.location.protocol == "https:";
        //https包含http资源返回true
        if (is_https_domain && !is_https_resource) {
          return true;
        } else {
          return false;
        }
      } else {
        return false;
      }
    },
    //1.正在直播区间  2.直播还没开始  3.直播结束
    live_status() {
      const { liveEndTime, liveStartTime } = this.chapter_obj;
      let currentTime = new Date().getTime();
      if (liveStartTime <= currentTime && currentTime < liveEndTime) {
        return 1;
      } else if (liveStartTime > currentTime) {
        return 2;
      } else if (liveEndTime < currentTime) {
        return 3;
      }
    },
    //1.允许拼团  2.拼团还没开始  3.拼团结束
    group_booking_status() {
      const { endTime, startTime } = this.gbConfig;
      let currentTime = new Date().getTime();
      if (startTime <= currentTime && currentTime < endTime) {
        return 1;
      } else if (startTime > currentTime) {
        return 2;
      } else if (endTime < currentTime) {
        return 3;
      }
    },
    isShowSmallMemberAdvert() {
      if (this.member_config.isOpenMember === 1 && this.memberList.length > 0) {
        if (
          JSON.parse(this.memberList[0].majorIds).includes(
            this.course_obj.majorId
          )
        ) {
          // console.log("该课程在初级免费专业中");
          return true;
        } else if (
          JSON.parse(this.memberList[0].courseIds).includes(this.course_obj.id)
        ) {
          // console.log("该课程在初级免费课程中");
          return true;
        } else {
          return false;
        }
      } else {
        return false;
      }
    },
    isShowMiddleMemberAdvert() {
      if (this.member_config.isOpenMember === 1 && this.memberList.length > 0) {
        if (
          JSON.parse(this.memberList[1].majorIds).includes(
            this.course_obj.majorId
          )
        ) {
          // console.log("该课程在中级免费专业中");
          return true;
        } else if (
          JSON.parse(this.memberList[1].courseIds).includes(this.course_obj.id)
        ) {
          // console.log("该课程在中级免费课程中");
          return true;
        } else {
          return false;
        }
      } else {
        return false;
      }
    },
    isShowHighMemberAdvert() {
      if (this.member_config.isOpenMember === 1 && this.memberList.length > 0) {
        if (
          JSON.parse(this.memberList[2].majorIds).includes(
            this.course_obj.majorId
          )
        ) {
          // console.log("该课程在高级免费专业中");
          return true;
        } else if (
          JSON.parse(this.memberList[2].courseIds).includes(this.course_obj.id)
        ) {
          // console.log("该课程在高级免费课程中");
          return true;
        } else {
          return false;
        }
      } else {
        return false;
      }
    },
    is_related_member() {
      if (this.kl_md.KLHY == 1) {
        if (this.member_config.isOpenMember === 1) {
          if (
            !this.isShowSmallMemberAdvert &&
            !this.isShowMiddleMemberAdvert &&
            !this.isShowHighMemberAdvert
          ) {
            return false;
          } else {
            if (Object.keys(this.user_member).length > 0) {
              return false;
            } else {
              return true;
            }
          }
        } else {
          return false;
        }
      } else {
        return false;
      }
    },
    member_related() {
      let text = "";
      if (this.isShowSmallMemberAdvert) {
        text = this.member_config.smallMemberName;
      }
      if (this.isShowMiddleMemberAdvert) {
        text += "、" + this.member_config.middleMemberName;
      }
      if (this.isShowHighMemberAdvert) {
        text += "、" + this.member_config.highMemberName;
      }
      return text;
    }
  },
  watch: {},
  deactivated() {
    // let scroll_heigth = document.documentElement.scrollTop || document.body.scrollTop;
    // this.scroll_heigth = scroll_heigth;
    window.removeEventListener("scroll", this.eventListener);
    Array.from(document.querySelectorAll(".launch-btn")).forEach(item => {
      item.removeEventListener("launch", this.launchMinigram);
      item.removeEventListener("error", this.errorMinigram);
    });
  },
  beforeDestroy() {
    window.removeEventListener("scroll", this.eventListener);
    Array.from(document.querySelectorAll(".launch-btn")).forEach(item => {
      item.removeEventListener("launch", this.launchMinigram);
      item.removeEventListener("error", this.errorMinigram);
    });
  },
  activated() {
    this.initPage();
    this.active = "introduce";
    if (process.client) {
      window.addEventListener("scroll", this.eventListener);
      window.scrollTo(0, 0);
    }
  },
  methods: {
    ...mapActions(["initMember","initBuyRecord"]),
    ...mapMutations([
      "SET_IS_LOADING",
      "UPDATE_USERINFO",
      "UPDATE_BUYRECORD_LIST",
      "UPDATE_SIGN_AGREEMENT_LIST"
    ]),
    allCommentHandle(){
      this.$router.push({ path: '/m/comment-list', query: { courseId: this.courseId }})
    },
    //设置我的作业报告的数据
    setTask(obj) {
      if (obj && obj.taskType == 2) {
        this.taskObj = obj;
      } else {
        console.log("跳转");
        this.$router.push("/m/task-paper?taskId=" + obj.id);
      }
    },
    afterRead(file) {
      let params = {
        userId: this.user_info.id,
        file: file,
        taskId: this.taskObj.id
      };
      this.uploadFile(params);
      return false;
    },
    async uploadFile(params) {
      this.SET_IS_LOADING(true);
      console.log(params);
      let fd = new FormData();
      Object.keys(params).forEach(i => {
        if (params[i] || params[i] === 0) {
          fd.append(i, params[i]);
        }
      });
      let result = await saveUserTask(fd);
      if (result && result.data && result.data.code == 200) {
        this.$toast("上传作业成功！");
        this.getMyTask();
      } else if (result && result.data && result.data.code == 1001) {
        this.$toast(result.data.msg);
      } else {
        this.$toast("上传作业失败！");
      }
      this.SET_IS_LOADING(false);
      return false;
    },
    //获取我的作业
    async getMyTask() {
      this.SET_IS_LOADING(true);
      let params = {
        courseId: this.courseId
      };
      let result = await getMyTaskList(params);
      if (result && result.data && result.data.code == 200) {
        this.myTaskList = result.data.data.rows.map(item => {
          return {
            ...item,
            videoHierarchy: item.videoHierarchy
              ? JSON.parse(item.videoHierarchy)
              : []
          };
        });
      } else {
        this.$Message.error(this.$t("locale.pc.classroom.t43"));
      }
      this.SET_IS_LOADING(false);
    },
    /* 微信小程序跳转 */
    wxLivePath(item) {
      let userId = "student-" + this.user_info.id;
      return `/pages/meeting/meeting?userId=${userId}&authorization=${this.token}&roomId=${item.id}&teacherId=${this.teacher_obj.id}`;
    },
    validateIdNumber(value) {
      if (value === "") {
        return false;
      } else {
        if (
          !/^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/.test(
            value
          )
        ) {
          return false;
        }
        return true;
      }
    },
    // 提交协议签署
    async handleSubmitAgreement(values) {
      let params = {
        ...this.agreementForm,
        userId: this.user_info.id,
        agreementId: this.courseAgreementObj.id
      };
      let result = await saveCourseAgreement(params);
      if (result && result.data && result.data.code == 200) {
        this.UPDATE_SIGN_AGREEMENT_LIST(result.data.data);
      } else {
        this.$Message.error("签署失败");
      }
    },
    // 获取课程协议
    async getCourseAgreement() {
      this.SET_IS_LOADING(true);
      let result = await getCourseAgreement(this.courseId);
      if (result && result.data && result.data.code == 200) {
        this.courseAgreementObj = result.data.data;
      } else {
        this.$Message.error("获取失败");
      }
      this.SET_IS_LOADING(false);
    },
    /* 课程收藏事件 */
    async collectionHandle() {
      /*收藏 */
      if (this.course_obj.isCollect == 0) {
        let params = {
          type: 1,
          userId: this.user_info.id,
          targetId: this.courseId
        };
        let result = await saveCollection(params);
        if (result && result.data && result.data.code == 200) {
          this.course_obj = {
            ...this.course_obj,
            isCollect: 1
          };
          this.$toast("收藏成功");
        }
        /* 取消收藏 */
      } else if (this.course_obj.isCollect == 1) {
        let result = await deleteCollection(
          this.course_obj.id + "/" + this.user_info.id
        );
        if (result && result.data && result.data.code == 200) {
          this.course_obj = {
            ...this.course_obj,
            isCollect: 0
          };
          this.$toast("取消收藏");
        }
      }
    },
    twoNumber(number) {
      return (Array(2).join(0) + number).slice(-2);
    },
    getGroupCount(item) {
      if (!item) {
        return -1;
      }
      const { troopsTime } = this.gbConfig;
      let time_far =
        new Date(item.creatTime).getTime() +
        troopsTime * 60 * 1000 -
        new Date().getTime();
      if (time_far > 0) {
        return time_far;
      } else {
        return -1;
      }
    },
    //领取优惠卷
    async receiveCoupon(id) {
      console.log("优惠卷id", id);
      if (process.client) {
        if (!this.token && Object.keys(this.user_info).length == 0) {
          this.$router.replace("/m/login");
          return;
        }
      }
      let params = {
        userId: this.user_info.id,
        couponId: id
      };
      let result = await receiveCoupon(params);
      if (result && result.data && result.data.code == 200) {
        this.$toast("领取成功！");
      } else if (result && result.data && result.data.code == 400) {
        this.$toast("你已经领取过了优惠卷，请勿重复领取！");
      } else {
        this.$toast("领取失败！");
      }
      // console.log("领取优惠卷",result);
    },
    //格式化时间
    formatDate(date) {
      var date = new Date(date);
      var YY = date.getFullYear() + "-";
      var MM =
        (date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1) + "-";
      var DD = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
      var hh =
        (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
      var mm =
        (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) +
        ":";
      var ss =
        date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
      return YY + MM + DD + " " + hh + mm + ss;
    },
    //格式化时间
    trimDate(date) {
      var date = new Date(date);
      var YY = date.getFullYear() + "-";
      var MM =
        (date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1) + "-";
      var DD = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
      var hh =
        (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
      var mm =
        (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) +
        ":";
      var ss =
        date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
      return YY + MM + DD;
    },
    async toBuy() {
      if (process.client) {
        if (!this.token && Object.keys(this.user_info).length == 0) {
          this.$router.replace("/m/login");
          return;
        }
      }
      if(this.buyStatus){
        this.$toast("该课程尚未开放购买哦~");
        return;
      }
      if (this.isPublishedBefore) {
        this.$toast("您已经发起过该课程的拼单，暂时无法单独购买哦~");
        return false;
      }
      if (this.course_obj.isFree) {
        this.toFreeBuy();
      } else {
        this.$router.push({
          path: "/m/order",
          query: {
            id: this.course_obj.id
          }
        });
      }
    },
    async toFreeBuy() {
      this.SET_IS_LOADING(true);
      let params = {
        courseId: this.courseId,
        userId: this.user_info.id,
        price: 0.0
      };
      console.log(params);
      let result = await saveOrder(params);
      // console.log(result);
      // return
      if (result && result.data && result.data.code == 200) {
        const { balance, id, courseId, userId, deleted } = result.data.data;
        let update_obj = {
          balance
        };
        let course_update_obj = {
          id,
          courseId,
          userId,
          deleted
        };
        // console.log("更新课程",course_update_obj)
        // console.log("更新课程",result.data.data)
        // this.$store.dispatch({
        //   type: "checkBingWechatStatus",
        //   payload: {
        //     type: "apply",
        //     params: {
        //       courseName: this.course_obj.courseName,
        //       userId
        //     }
        //   }
        // });
        this.UPDATE_USERINFO(update_obj);
        this.UPDATE_BUYRECORD_LIST(course_update_obj);
        this.SET_IS_LOADING(false);
        this.$toast("报名成功！");
        // 隐藏底部购买按钮
        this.is_had_course = true;
        // 判断是否需要跳转
        if (
          this.course_obj.isLive == 0 ||
          (this.course_obj.isLive == 2 && !this.course_obj.videoInfo)
        ) {
          this.$router.push({
            path: "/m/course-play",
            query: {
              id: this.course_obj.id
            }
          });
        }
      }
    },
    eventListener() {
      if (
        this.$refs["course-introduce"].getBoundingClientRect().top <= 100 &&
        this.isFixedNav == false
      ) {
        this.isFixedNav = true;
      } else if (
        this.$refs["course-introduce"].getBoundingClientRect().top > 100 &&
        this.isFixedNav == true
      ) {
        this.isFixedNav = false;
      }
      // console.log("滚动")
      // console.log(this.$refs['course-introduce'].getBoundingClientRect().top)
      // console.log(this.$refs.coursemenu.offsetTop)
    },
    set_had_course() {
      let res = this.buy_record_list.filter(i => i.courseId == this.courseId);
      console.log("拥有该门课程", res);
      if (res.length > 0 && res[0].deleted === 0) {
        this.is_had_course = true;
      } else {
        this.is_had_course = false;
      }
    },
    async pushRouter(item) {
      if (item.children && item.children.length > 0) {
        return;
      }
      // console.log(item);
      // return;
      // 保留阿里云直播,跳转到指定的直播地址
      if ((item.isLive == 1 || item.isLive == 4) && item.videoInfo) {
        // console.log(item); // 直播id
        let result = await getVideoUrl(item.videoInfo.id);
        if (result && result.data && result.data.code == 200) {
          location.href = result.data.data.liveUrl;
        } else if (result && result.data && result.data.code == 1001) {
          this.$Message.error(result.data.msg);
        } else {
          this.$Message.error("数据请求失败");
        }
        // 拦截加载项和阻止函数
        this.SET_IS_LOADING(false);
        return;
      } else if (item.isLive == 2 && item.videoInfo) {
        this.$toast("小班课暂不支持在在手机上观看");
        return
      }
      if (this.token && Object.keys(this.user_info).length > 0) {
        /* 微信环境中 这里在小班课的前提下根据欢拓云的字段判断要不要跳小程序 */
        if (
          !this.is_hidden_content &&
          this.is_in_wechat &&
          item.isLive == 2 &&
          !item.videoInfo
        ) {
          /* 在小程序环境中小班课直播跳转到小程序 */
          if (this.is_in_minigram) {
            wx.miniProgram.navigateTo({
              url: this.wxLivePath(item),
              success: function() {
                console.log("成功跳转小程序");
              },
              fail: function() {
                console.log("跳转小程序失败");
              },
              complete: function() {
                console.log("完成");
              }
            });
            /* 调起微信小程序 */
          } else {
          }
        } else {
          this.$router.push({
            path: "/m/course-play",
            query: {
              id: this.courseId,
              chapterId: item.id
            }
          });
        }
      } else {
        this.$dialog
          .confirm({
            title: "提示",
            message: "您尚未登录，请先登录再观看哟！"
          })
          .then(() => {
            this.$router.replace("/m/login");
          })
          .catch(() => {
            return false;
          });
      }
    },
    menuHandle(type) {
      this.active = type;
      // let current_top = this.$refs["course-"+type].offsetTop - 50;
      let current_top = this.$refs["course-" + type].offsetTop - 100;
      // let current_top = 0;
      // if(type == 'introduce'){
      //   current_top = this.$refs["course-"+type].offsetTop - 100;
      // }else if(this.isFixedNav){
      //   current_top = this.$refs["course-"+type].offsetTop - 100;
      // }else{
      //   current_top = this.$refs["course-"+type].offsetTop - 100;
      // }
      // if(type == 'introduce'){
      //   current_top = this.$refs["course-"+type].offsetTop - 50;
      // }else if(this.isFixedNav){
      //   current_top = this.$refs["course-"+type].offsetTop - 100;
      // }else{
      //   current_top = this.$refs["course-"+type].offsetTop - 150;
      // }
      // console.log(current_top)
      // console.log(this.$refs["course-"+type].offsetTop);
      // document.getElementById('page-mobile-course_detail')
      window.scrollTo(0, current_top);
    },
    async getCourseCoupon() {
      let result = await getCourseCoupon(this.courseId);
      if (result && result.data && result.data.code == 200) {
        const { data } = result.data;
        this.couponList = data;
      } else {
      }
    },
    async getData() {
      return new Promise(async (res, rej) => {
        this.SET_IS_LOADING(true);
        let result = await getCourse({
          id: this.courseId
        });
        if (result && result.data && result.data.code == 200) {
          const { data } = result.data;
          if (data && data.rows && data.rows.length > 0) {
            // this.course_obj = data.rows[0];
            // 加一层折扣时间的判断,不在折扣时间内判定为不是折扣课程
            let course = data.rows[0];
            let currentTime = new Date().getTime();
            if(!(course.isDiscount == 1 && currentTime >= course.discountStartTime && course.discountEndTime >= currentTime)){
              this.course_obj = {
                ...course,
                isDiscount:0
              }
            }else{
              this.course_obj = course;
            }
            this.getTeacherFun();
            this.getCourseCoupon();
            this.getCollectList();
          }
        } else {
          this.$toast(
            this.$t("locale.mobile.courseDetail.t18") + result &&
              result.data &&
              result.data.msg
          );
        }
        this.SET_IS_LOADING(false);
        res();
      }).then();
    },
    async getCollectList() {
      if (this.token && Object.keys(this.user_info).length > 0) {
        this.SET_IS_LOADING(true);
        let params = {
          targetId: this.courseId,
          type: 1,
          userId: this.user_info.id
        };
        let result = await getCollectList(params);
        if (result && result.data && result.data.code == 200) {
          if (result.data.data.rows.length > 0) {
            this.course_obj = {
              ...this.course_obj,
              isCollect: 1
            };
          } else {
            this.course_obj = {
              ...this.course_obj,
              isCollect: 0
            };
          }
        } else {
          this.$toast("获取失败！");
        }
        this.SET_IS_LOADING(false);
      } else {
        return;
      }
    },
    arrToTree(trimChapterList) {
      let _LEVEL_OBJECT = {};
      //找出最深的层数
      let _MAX_ = trimChapterList.reduce((accumulator, currentValue) => {
        if (accumulator.chapterLevel > currentValue.chapterLevel) {
          return accumulator;
        } else {
          return currentValue;
        }
      }).chapterLevel;
      if (!_MAX_) {
        return trimChapterList;
      }
      for (let i = 1; i < _MAX_ + 1; i++) {
        _LEVEL_OBJECT = {
          ..._LEVEL_OBJECT,
          [i]: trimChapterList
            .map((item, index) => {
              if (item.chapterLevel == i) {
                return item;
              }
            })
            .filter(item => item !== undefined)
        };
      }
      for (let i = _MAX_; i >= 1; i--) {
        if (i < _MAX_) {
          _LEVEL_OBJECT[i] = _LEVEL_OBJECT[i].map((item, index) => {
            return {
              ...item,
              children: _LEVEL_OBJECT[i + 1]
                .map((item2, index2) => {
                  if (item2.fatherLevelId == item.id) {
                    return item2;
                  }
                })
                .filter(item2 => item2 !== undefined)
            };
          });
        }
      }
      return _LEVEL_OBJECT[1];
    },
    async getChapterList() {
      return new Promise(async (res, rej) => {
        this.SET_IS_LOADING(true);
        let result = await getChapter({
          courseId: this.courseId
        });
        if (result && result.data && result.data.code == 200) {
          const { data } = result.data;
          if (data && data.rows && data.rows.length > 0) {
            this.chapter_list = data.rows;
            let trimChapterList = [];
            trimChapterList = this.chapter_list.map(i => {
              return {
                ...i,
                children: []
              };
            });
            // this.chapter_tree = this.arrToTree(trimChapterList);
            this.chapter_tree = this.orderList(
              this.handleTree(trimChapterList, "id", "fatherLevelId")
            );
          }
          this.set_had_course();
        } else {
          this.$toast(
            this.$t("locale.mobile.courseDetail.t19") + result &&
              result.data &&
              result.data.msg
          );
        }
        this.SET_IS_LOADING(false);
        res();
      }).then();
    },
    /**
     * 构造树型结构数据
     * @param {*} data 数据源
     * @param {*} id id字段 默认 'id'
     * @param {*} parentId 父节点字段 默认 'parentId'
     * @param {*} children 孩子节点字段 默认 'children'
     */
    handleTree(data, id, parentId, children) {
      let config = {
        id: id || "id",
        parentId: parentId || "parentId",
        childrenList: children || "children"
      };

      var childrenListMap = {};
      var nodeIds = {};
      var tree = [];
      for (let d of data) {
        let parentId = d[config.parentId];
        if (childrenListMap[parentId] == null) {
          childrenListMap[parentId] = [];
        }
        nodeIds[d[config.id]] = d;
        childrenListMap[parentId].push(d);
      }
      for (let d of data) {
        let parentId = d[config.parentId];
        if (nodeIds[parentId] == null) {
          tree.push(d);
        }
      }
      for (let t of tree) {
        adaptToChildrenList(t);
      }
      function adaptToChildrenList(o) {
        if (childrenListMap[o[config.id]] !== null) {
          o[config.childrenList] = childrenListMap[o[config.id]]
            ? childrenListMap[o[config.id]]
            : [];
        }
        if (o[config.childrenList]) {
          for (let c of o[config.childrenList]) {
            adaptToChildrenList(c);
          }
        }
      }
      return tree;
    },
    // 排序
    orderList(data) {
      data.map(item => {
        if (item.children && item.children.length > 0) {
          return this.orderList(item.children);
        } else {
          return item;
        }
      });
      return data.sort((a, b) => {
        return b.orderNumber - a.orderNumber;
      });
    },
    async getTeacherFun() {
      this.SET_IS_LOADING(true);
      let params = {
        id: Number(this.course_obj.teacher)
      };
      let result = await getTeacher(params);
      console.log(result);
      if (result && result.status == 200 && result.data) {
        this.teacher_obj = result.data;
        this.SET_IS_LOADING(false);
      } else {
        this.SET_IS_LOADING(false);
        this.$toast(
          this.$t("locale.mobile.courseDetail.t19") + result &&
            result.data &&
            result.data.msg
        );
      }
    },
    /* 微信小程序相关 */
    async getWxMiniInfo() {
      let params = {
        url: window.location.href
      };
      let result = await getWxMiniInfo(params);
      console.log("获取微信小程序相关：", result);
      if (result && result.data && result.data.code == 200) {
        this.wxMinigramInfo = {
          ...result.data.data
        };
        this.$nextTick(() => {
          if (process.client) {
            const { appId, noncestr, sign, timestamp } = this.wxMinigramInfo;
            launchWxMiniProgram(
              {
                appId,
                timeStamp: timestamp,
                nonceStr: noncestr,
                signature: sign
              },
              () => {
                Array.from(document.querySelectorAll(".launch-btn")).forEach(
                  item => {
                    item.addEventListener("launch", this.launchMinigram);
                    item.addEventListener("error", this.errorMinigram);
                  }
                );
              }
            );
          }
        });
      }
    },
    launchMinigram(e) {
      console.log("跳转微信小程序成功！", e);
    },
    errorMinigram(e) {
      console.log("跳转微信小程序失败！", e.detail);
      errorCb && errorCb();
    },
    initPage() {
      // console.log("downloadFile",wx.miniProgram.downloadFile);
      if (process.client) {
        this.$nextTick(()=>{
          document.body.scrollTop = 0
          document.documentElement.scrollTop = 0
        })
        /* wx-open-launch-weapp IOS bug */
        if (this.is_ios && this.is_in_wechat && !this.is_in_minigram) {
          if (!sessionStorage.getItem("reloadpage")) {
            sessionStorage.setItem("reloadpage", 1);
            location.reload();
          }
        }
      }
      

      Object.assign(this.$data, originState);
      this.agreementForm = {};
      this.getData();
      // this.getBuyCourse();
      // this.set_had_course();
      this.getChapterList();
      this.getCommentList();
      if (this.token && Object.keys(this.user_info).length > 0) {
        this.initMember();
        this.initBuyRecord();
        this.getMemberConfig();
        this.getMemberList();
        this.getMyTask();
        this.getCourseAgreement();
        this.getGroupBooking();
        this.$nextTick(() => {
          if (this.is_in_wechat && !this.is_in_minigram) {
            this.getWxMiniInfo();
          }
        });
      }

      // this.$nextTick(() => {
      //   if (this.kl_md.KLPT == 1) {

      //   }
      // });
    },
    async getMemberConfig() {
      this.SET_IS_LOADING(true);
      let result = await getMemberConfig();
      console.log("result会员", result);
      if (result && result.data && result.data.code == 200) {
        this.member_config = {
          smallMemberName: result.data.data.smallMemberName,
          middleMemberName: result.data.data.middleMemberName,
          highMemberName: result.data.data.highMemberName,
          isOpenMember: result.data.data.isOpenMember
        };
        console.log(this.member_info);
      } else {
      }
      this.SET_IS_LOADING(false);
    },
    async getMemberList() {
      this.SET_IS_LOADING(true);
      let result = await getMemberList();
      console.log("result", result);
      if (result && result.data && result.data.code == 200) {
        this.memberList = result.data.data.rows.map(item => {
          return { ...item, introduction: JSON.parse(item.introduction) };
        });
      } else {
      }
      this.SET_IS_LOADING(false);
    },
    // async getBuyCourse(){
    //   let result = await downloadFile(url);

    // },
    //blob转base64在调用downloadjs下载
    async handleDownload(url, fileName) {
      if (!url || url == "null") {
        return;
      }
      if (process.client) {
        if (window.hasOwnProperty("flutter_inappwebview")) {
          return;
        }
        const { download } = require("~/static/js/download2.js");
        let result = await downloadFile(url);
        // console.log("result:", result);
        if (result && result.status == 200) {
          let mime_type = getMimeType(url);
          download(result.data, fileName + "." + mime_type.str, mime_type.mime);
        }
      }
    },
    //获取拼团商品信息
    async getGroupBooking() {
      this.SET_IS_LOADING(true);
      let result = await getGroupBookingListByCourse({
        sort: "id desc",
        goodsId: this.courseId
      });
      console.log("拼团信息：", result);
      if (result && result.data && result.data.code == 200) {
        const { rows } = result.data.data;
        if (rows.length > 0) {
          this.gbConfig = { ...rows[0], is_set: true };
        } else {
          this.gbConfig = { ...rows[0], is_set: false };
        }
        this.getGroupsByCourse();
        this.checkIsPublishBefore();
      } else {
      }
      this.SET_IS_LOADING(false);
    },
    //获取拼团
    async getGroupsByCourse() {
      this.SET_IS_LOADING(true);
      const { id } = this.gbConfig;
      if (id) {
        let result = await getGroupBookingGroupsByCourse({
          goodsId: this.gbConfig.id,
          status: 1
        });
        if (result && result.data && result.data.code == 200) {
          const { rows, total } = result.data.data;
          if (rows.length > 0) {
            let groupList = rows.map(i => {
              return {
                ...i,
                userIds: JSON.parse(i.userIds),
                userList: i.userList.filter(item => item)
              };
            })
            this.groupList = groupList.filter(i => {
                let groupPurchaseGoods = i.groupPurchaseGoods;
                if((i.creatTime + (groupPurchaseGoods.troopsTime * 60 * 1000) - new Date().getTime()) > 0 && i.status == 1){
                  return true;
                }else{
                  return false;
                }
            }); //过滤过期的和为到开始时间的
            this.groupNum = this.groupList.length;
          } else {
            this.groupList = [];
            this.groupNum = 0;
          }
        } else {
        }
      }
      this.SET_IS_LOADING(false);
    },
    //是否发起过该商品的拼单
    async checkIsPublishBefore() {
      this.SET_IS_LOADING(true);
      const { id } = this.gbConfig;
      let result = await getGroupBookingGroupsByCourseAndUser({
        goodsId: id,
        userId: this.user_info.id
      });
      if (result && result.data && result.data.code == 200) {
        const { data } = result.data;
        if (data && !data.goodsTroopsStatus) {
          this.isPublishedBefore = true;
        } else {
          this.isPublishedBefore = false;
        }
      } else {
        this.isPublishedBefore = false;
      }
      this.SET_IS_LOADING(false);
    },
    joinGroup(type) {
      if (!this.token && Object.keys(this.user_info).length == 0) {
        this.$router.replace("/m/login");
        return;
      }
      if(this.buyStatus){
        this.$toast("该课程尚未开放购买哦~");
        return;
      }
      //发起拼团
      if (type == "self") {
        this.$router.push({
          path: "/m/order",
          query: {
            id: this.course_obj.id,
            groupBooking: 1
          }
        });
        //加入拼团
      } else if (type == "group") {
        this.$router.push({
          path: "/m/order",
          query: {
            id: this.course_obj.id,
            groupBooking: 1,
            joinGroup: this.current_group.id
          }
        });
      }
    },
    handleFinish(type, item) {
      if (type == "list") {
        this.groupList = this.groupList.filter(i => i.id != item.id);
        this.groupNum = this.groupNum - 1;
      } else if (type == "current") {
        this.groupList = this.groupList.filter(
          i => i.id != this.current_group.id
        );
        this.groupNum = this.groupNum - 1;
        this.is_groupBooking_dialog = false;
        this.is_groupBooking_join = false; //参与拼团弹窗
      }
      if (this.isPublishedBefore) {
        window.location.reload();
      }
    },
    handleJoinGroup(item) {
      console.log("item:", item);
      //如果已经登录判断该拼单是否是自己发起的
      if (this.token && Object.keys(this.user_info).length != 0) {
        if (item.userId == this.user_info.id) {
          this.$toast("不能参与自己的拼单哦~");
          return false;
        }
      }
      this.current_group = {
        ...item
      };
      this.is_groupBooking_dialog = false;
      this.is_groupBooking_join = true;
    },
    async getCommentList() {
      this.SET_IS_LOADING(true);
      let params = {
        courseId: this.courseId,
        offset: 0,
        limit: 1,
        sort: "id desc",
        rateType: '0'
      };
      let result = await getCourseCommentList(params);
      if (result && result.data && result.data.code == 200) {
        let data = result.data.data.rows.map(item => {
          return {
            ...item,
            acName: item.acName ? item.acName.substr(0, 1) + "****" : "无****"
          };
        });
        this.commentList = data;
        this.commentTotal = result.data.data.total;
      } else {
        this.$toast("获取失败！");
      }
      this.SET_IS_LOADING(false);
    },
  },
  created() {
    this.initPage();
  },
  mounted() {
    if (process.client) {
      window.addEventListener("scroll", this.eventListener);
    }
  }
};
</script>

<style lang="scss">
.page-mobile-course_detail {
  width: 100vw;
  min-height: 100vh;
  background-color: #f7f7fa;
  position: relative;
  @import "~/assets/css/richtext.scss";
  .graystyle{
    background: #d0caca !important;
    color: #504949 !important;
    border-color: #d0caca;
    font-size: .3rem;
  }
  .course-agreement {
    .van-button__text {
      font-size: 0.3rem;
    }
  }
  .collection {
    position: fixed;
    right: 0.2rem;
    top: 0.28rem;
    width: 0.3264rem;
    height: 0.3264rem;
    z-index: 2001;
    img {
      width: 100%;
      height: 100%;
      display: block;
    }
  }
  .coupon-content {
    width: 7.2rem;
    height: 1.8528rem;
    margin-bottom: 0.3rem;
    background-color: #ffffff;
    .coupon-box {
      width: 6.624rem;
      height: 1.8528rem;
      margin: 0 auto;
      display: flex;
      align-items: center;
      justify-content: space-between;
      background-image: url("/img/mobile/coupon_type.png");
      background-size: 100% 100%;
      background-repeat: no-repeat;
      .box-left {
        height: 1.5rem;
        width: 76%;
        display: flex;
        justify-content: space-between;

        .right-line {
          position: absolute;
          right: -0.1rem;
          top: 50%;
          transform: translateY(-50%);
          width: 0.1rem;
          height: 1.3rem;
          background-image: linear-gradient(
            to bottom,
            #fff 0%,
            #fff 50%,
            transparent 50%
          );
          background-size: 0.03rem 0.28rem;
          background-repeat: repeat-y;
        }
        .price {
          width: 30%;
          font-size: 0.3rem;
          line-height: 1.5rem;
          text-align: center;
          color: #ff343d;
          span {
            font-size: 0.6rem;
            position: relative;
            // font-weight: bold;
          }
        }
        .info {
          width: 70%;
          color: #fff;
          margin-top: 0.4rem;
          .max-time {
            font-size: 0.2496rem;
          }
          .info-time {
            margin-top: 0.1rem;
            font-size: 0.2112rem;
          }
        }
      }
      .box-right {
        width: 24%;
        height: 1.4rem;
        // border-left: 1px dotted #fff;
        color: #fff;
        text-align: center;
        line-height: 1.4rem;
        font-size: 0.2688rem;
      }
    }
  }
  .coupon-content:first-child {
    margin-top: 0.1rem;
  }
  .course-info {
    border-top: 0.026rem solid #f7f7fa;
    background: #ffffff;
    padding: 0.288rem;
    .course-img {
      width: 6.624rem;
      height: 3.6799999999999997rem;
      margin: 0rem auto 0.288rem;
      background-color: var(--theme-color);
      border-radius: 0.096rem;
      overflow: hidden;
      img {
        display: block;
        width: 100%;
        height: 100%;
      }
    }
    .course-name {
      margin-bottom: 0.2rem;
      color: #313233;
      font-weight: 700;
      font-size: 0.3rem;
    }
    .student-price {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin: 0 0 0.2rem;
      .student {
        color: #adb0b3;
        font-size: 0.2688rem;
      }
      .price {
        font-size: 0.3rem;
        color: var(--theme-color);
      }
    }
    .teacher {
      display: flex;
      // align-items: center;
      justify-content: space-between;
      border-top: 0.026rem solid #f7f7fa;
      padding-top: 0.2rem;
      .teacher-left {
        display: flex;
        align-items: center;
        .teacher-avatar {
          width: 0.5376rem;
          height: 0.5376rem;
          overflow: hidden;
          border-radius: 50%;
          background-color: var(--theme-color);
          img {
            width: 100%;
            height: 100%;
            border-radius: 50%;
            display: block;
          }
        }
        .teacher-name {
          margin: 0 0.14rem;
          font-size: 0.26rem;
          color: var(--theme-color);
        }
        img {
          width: 0.2304rem;
          height: 0.2304rem;
          display: block;
        }
      }
      .teacher-right {
        display: flex;
        align-items: center;
        img {
          width: 0.3648rem;
          height: 0.3648rem;
          display: block;
          background: var(--theme-color);
          margin-right: 0.1rem;
        }
        .count-time {
          font-size: 0.2688rem;
          color: #4a4b4d;
        }
      }
    }
  }
  .group-booking {
    margin-top: 0.2rem;
    padding: 0 0.2rem;
    background-color: #fff;
    .group-booking-info {
      position: relative;
      display: flex;
      height: 0.8rem;
      font-size: 0.32rem;
      line-height: 0.8rem;
      .info-left {
        flex: 1;
      }
      .info-right {
        font-size: 0.24rem;
        color: #9c9c9c;
        > i {
          font-size: 0.24rem;
          color: #9c9c9c;
        }
      }
      &::after {
        content: "";
        display: block;
        position: absolute;
        left: -0.2rem;
        bottom: 0;
        width: 7.2rem;
        height: 1px;
        background-color: #f2f2f2;
      }
    }
  }
  .list-container {
    height: 2.4rem;
    overflow: hidden;
    .list-item {
      position: relative;
      display: flex;
      height: 1.2rem;
      .item-left {
        display: flex;
        align-items: center;
        .user-avatar {
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 0.2rem;
          width: 0.8rem;
          height: 0.8rem;
          border-radius: 0.8rem;
          overflow: hidden;
          background-color: var(--theme-color);
          > img {
            width: 100%;
            height: 100%;
          }
          .avatar-alt {
            font-size: 0.3rem;
            color: #fff;
          }
        }
        .user-nackname {
          width: 2.2rem;
          font-size: 0.26rem;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
        }
      }
      .item-content {
        display: flex;
        flex-direction: column;
        justify-content: center;
        margin-left: 0.2rem;
        box-sizing: border-box;
        width: 2rem;
        text-align: right;
        .content-top {
          font-size: 0.22rem;
        }
        .content-bottom {
          margin-top: 0.1rem;
          font-size: 0.26rem;
          color: #999;
        }
      }
      .item-right {
        display: flex;
        flex: 1;
        align-items: center;
        justify-content: flex-end;
        margin-left: 0.2rem;
        .van-button {
          height: 0.55rem;
          line-height: 0.55rem;
        }
      }
      &:not(:last-child)::after {
        content: "";
        display: block;
        position: absolute;
        left: 0;
        bottom: -1px;
        width: 100%;
        height: 1px;
        background-color: #f2f2f2;
      }
    }
  }
  .groupBooking_dialog {
    width: 6.5rem;
    .list-container {
      margin-top: 0.32rem;
      padding: 0 0.1rem;
      max-height: 7.22rem;
      overflow: auto;
      .list-item {
        .item-left {
          .user-nackname {
            width: 1.9rem;
          }
          .user-avatar {
            margin-right: 0.1rem;
          }
        }
        .item-content {
          width: 2rem;
          .content-bottom {
            margin-left: 0.1rem;
            font-size: 0.24rem;
          }
        }
      }
    }
  }
  .groupBooking_join {
    width: 6.5rem;
    .van-hairline--left {
      background-color: var(--theme-color);
      color: #fff;
    }
    .join-container {
      margin-top: 0.32rem;
      .join-rest {
        display: flex;
        justify-content: center;
        flex-wrap: wrap;
        align-items: center;
        font-size: 0.24rem;
        text-align: center;
        .rest-num {
          color: var(--theme-color);
        }
      }
      .group-member {
        display: flex;
        justify-content: center;
        flex-wrap: wrap;
        padding: 0.3rem 0.5rem;
        .member-item {
          position: relative;
          display: flex;
          align-items: center;
          justify-content: center;
          margin: 0.1rem 0.2rem;
          width: 1rem;
          height: 1rem;
          border-radius: 1rem;
          border: 1px solid #ccc;
          background-color: var(--theme-color);
          img{
            width: 100%;
            height: 100%;
            display: block;
            overflow: hidden;
          }
          // overflow: hidden;
          .van-tag {
            top: 0;
            left: 0;
            position: absolute;
            transform: translateY(-50%);
          }
          .avatar-alt {
            font-size: 0.3rem;
            color: #fff;
          }
        }
        .leader {
          border: 1px solid goldenrod;
        }
        .pending {
          border: 1px dashed #ccc;
          background-color: #fff;
          > i {
            font-size: 0.8rem;
            color: #ccc;
          }
        }
      }
    }
  }
  // .fixed-box{
  //   width: 7.2rem;
  //   margin-top: .2rem;
  //   height: .864rem;
  //   border-bottom: .026rem solid #ededf1;
  //   background-color: #ffffff;
  // }
  .coupon {
    width: 7.2rem;
    height: 0.9rem;
    background-color: #ffffff;
    margin-top: 0.2rem;
    padding: 0 0.2rem;
    font-size: 0.3rem;
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-weight: bold;
    .coupon-right {
      display: flex;
      align-items: center;
    }
  }
  .course-menu {
    display: flex;
    justify-content: space-around;
    width: 7.2rem;
    margin-top: 0.2rem;
    z-index: 2000;
    background-color: #ffffff;
    border-bottom: 0.026rem solid #ededf1;
    &.task_item {
      .menu-item {
        width: 25%;
      }
    }
    .menu-item {
      font-size: 0.2688rem;
      width: 33.333%;
      height: 0.864rem;
      text-align: center;
      line-height: 0.864rem;
      color: #adafb3;
      position: relative;
    }
    .menu-item.active {
      color: #313233;
      &::after {
        content: "";
        display: block;
        position: absolute;
        left: 50%;
        bottom: 0;
        transform: translateX(-50%);
        width: 0.5rem;
        height: 0.05rem;
        background-color: var(--theme-color);
      }
    }
  }
  .course-menu.fixed {
    position: fixed;
    left: 0;
    top: 0.8rem;
    margin-top: 0;
  }
	.ql-editor{
		white-space: unset;
	}
  .course-container {
    padding: 0.288rem;
    background-color: #ffffff;
    .course-introduce {
      margin-bottom: 0.3rem;
      .title {
        padding-left: 0.2rem;
        font-size: 0.3rem;
        font-weight: bold;
        color: #313233;
        position: relative;
        margin-bottom: 0.2rem;
        &::after {
          content: "";
          display: block;
          width: 0.03rem;
          height: 0.384rem;
          background-color: var(--theme-color);
          position: absolute;
          left: 0;
          top: 50%;
          transform: translateY(-50%);
        }
      }
    }
    .course-chapter {
      margin-bottom: 0.3rem;
      .title {
        padding-left: 0.2rem;
        font-size: 0.3rem;
        font-weight: bold;
        color: #313233;
        position: relative;
        margin-bottom: 0.2rem;
        &::after {
          content: "";
          display: block;
          width: 0.03rem;
          height: 0.384rem;
          background-color: var(--theme-color);
          position: absolute;
          left: 0;
          top: 50%;
          transform: translateY(-50%);
        }
      }
      .chapter-box {
        .chapter-list {
          .chapter-title-one {
            background: #f0f4f7;
            color: #3d3f42;
            font-size: 0.288rem;
            padding: 0.2rem;
            font-weight: bold;
          }
          .chapter-title-two {
            padding: 0.2rem 0.4rem;
            background: #f0f4f7;
            color: #3d3f42;
            font-size: 0.288rem;
            font-weight: bold;
          }

          .chapter-one,
          .chapter-two {
            padding: 0.2rem;
            font-size: 0.288rem;
            color: #3d3f42;
            display: flex;
            justify-content: space-between;
            .chapter-left {
              flex: 8;
            }
            .chapter-right {
              flex: 2;
              font-size: 0.2304rem;
              height: 0.46rem;
              border: 0.02rem solid var(--theme-color);
              text-align: center;
              line-height: 0.46rem;
              background: #ffffff;
              color: var(--theme-color);
              border-radius: 0.1rem;
            }
          }
          .chapter-one {
            padding: 0.2rem 0.4rem;
          }
        }
      }
    }
    .course-file {
      // min-height: calc(100vh - 1.3rem);
      &.course_task {
        margin-bottom: 0.3rem;
      }
      &.un_course_task {
        min-height: calc(100vh - 1.3rem);
      }
      .title {
        padding-left: 0.2rem;
        font-size: 0.3rem;
        font-weight: bold;
        color: #313233;
        position: relative;
        margin-bottom: 0.2rem;
        &::after {
          content: "";
          display: block;
          width: 0.03rem;
          height: 0.384rem;
          background-color: var(--theme-color);
          position: absolute;
          left: 0;
          top: 50%;
          transform: translateY(-50%);
        }
      }
      .file-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-bottom: 0.026rem solid #ededf1;
        padding: 0.2rem;
        .item-left {
          width: 80%;
          font-size: 0.288rem;
          color: var(--theme-color);
        }
        .item-right {
          font-size: 0.2304rem;
          height: 0.46rem;
          width: 0.8448rem;
          border-radius: 0.1rem;
          border: 0.02rem solid var(--theme-color);
          text-align: center;
          line-height: 0.46rem;
          background: #ffffff;
          color: var(--theme-color);
        }
      }
    }
    .course-task {
      min-height: calc(100vh - 1.3rem);
      .title {
        padding-left: 0.2rem;
        font-size: 0.3rem;
        font-weight: bold;
        color: #313233;
        position: relative;
        margin-bottom: 0.2rem;
        &::after {
          content: "";
          display: block;
          width: 0.03rem;
          height: 0.384rem;
          background-color: var(--theme-color);
          position: absolute;
          left: 0;
          top: 50%;
          transform: translateY(-50%);
        }
      }
      .task-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-bottom: 0.026rem solid #ededf1;
        padding: 0.2rem;
        .item-left {
          width: 75%;
          font-size: 0.288rem;
          color: var(--theme-color);
        }
        .item-right {
          font-size: 0.2304rem;
          height: 0.46rem;
          width: 1.2rem;
          border-radius: 0.1rem;
          // border: 0.02rem solid var(--theme-color);
          text-align: center;
          line-height: 0.46rem;
          background: #ffffff;
          // color: var(--theme-color);
        }
      }
    }
    .course_comment{
      border-top: 1px solid #ddd;
      border-bottom: 1px solid #ddd;
      padding: .1536rem 0rem .2688rem;
      margin-bottom: .1536rem;
      .comment_title{
        display: flex;
        justify-content: space-between;
        align-items: center;
        color: #000;
        font-size: .3rem;
        margin-bottom: .3072rem;
        span:last-child{
          font-size: .2688rem;
        }
      }
      .comment_list{
        .comment_item{
          .comment_user{
            display: flex;
            margin-bottom: .1536rem;
            position: relative;
            .top_tag{
              position: absolute;
              right: 0;
              top: 0;
            }
            .comment_avatar{
              display: block;
              width: .61rem;
              height: .61rem;
              margin-right: .2rem;
              overflow: hidden;
              background: var(--theme-color);
              border-radius: 50%;
            }
            .comment_username{
              margin-bottom: .03rem;
              color: #000;
            }
            // .comment_rate{}
          }
          .comment_content{
            font-size: .2688rem;
            line-height: .384rem;
            .comment_text{
              word-break: break-word;
              word-wrap: break-word;
              overflow: hidden;
              color: #000;
            }
            .comment_time{
              margin-top: .1536rem;
              color: #777;
            }
          }
        }
      }
      .comment_empty{
        color: #000;
        font-size: .2688rem;
        line-height: .384rem;
      }
    }
  }
  .bottom-area {
    height: 1rem;
    .btn-buy {
      box-sizing: content-box;
      position: fixed;
      left: 0;
      bottom: 0;
      width: 7.2rem;
      height: 1rem;
      box-shadow: 0 0 0.1rem 0 rgba(0, 0, 0, 0.1);
      display: flex;
      align-items: center;
      background-color: #fff;
      z-index: 99;
      > .van-button {
        margin: 0 0.2rem;
        border-radius: 0.5rem;
      }
    }
    @supports (bottom: constant(safe-area-inset-bottom)) {
      .btn-buy {
        padding-bottom: constant(safe-area-inset-bottom);
      }
    }
    @supports (bottom: env(safe-area-inset-bottom)) {
      .btn-buy {
        padding-bottom: env(safe-area-inset-bottom);
      }
    }
  }
  .gb {
    // height: 2rem;
    // .btn-buy {
    //   display: flex;
    //   flex-direction: column;
    //   justify-content: space-around;
    //   align-items: center;
    //   height: 2rem;
    // }
    .btn-buy {
      padding: 0 0.2rem;
      box-sizing: border-box;
      justify-content: space-between;
      .btn-right {
        border-top-left-radius: 0;
        border-bottom-left-radius: 0;
      }
      .btn-left {
        border-bottom-right-radius: 0;
        border-top-right-radius: 0;
      }
      .van-button {
        margin: 0;
        width: 3.38rem;
        .btn-price {
          font-size: 0.34rem;
          line-height: normal;
        }
        .btn-text {
          font-size: 0.22rem;
          line-height: normal;
        }
      }
    }
  }
  .sub-price {
    font-size: 0.26rem;
    color: #999;
    text-decoration: line-through;
  }
  .launch-btn {
  }
}
</style>
<style lang="scss" scope>
.page-mobile-course_detail {
  .course-agreement {
    z-index: 2005;
    overflow: hidden;
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.3);
    .agreement-box {
      position: relative;
      top: 1rem;
      width: 6.624rem;
      margin: 0 auto;
      background-color: #fff;
      z-index: 1005;
      outline: 0;
      border-radius: 0.1rem;
      overflow: hidden;
      .agreement-header {
        text-align: center;
        line-height: 0.7rem;
        font-size: 0.3072rem;
        border-bottom: 0.0096rem #ddd solid;
      }
      .agreement-body {
        box-sizing: border-box;
        padding: 0.1rem;
        min-height: 50vh;
        max-height: 50vh;
        overflow: auto;
      }
      .agreement-footer {
      }
    }
  }
}
</style>
